import { AppData } from "./app";
import { getRequestHeader, getResponseData } from "./request";

/**
 * 上传文件
 * @param url
 * @param filePath
 * @param formData
 * @param uploadTask
 */
export const uploadFile = <T>(
  url: string,
  filePath: string,
  formData?: AnyObject,
  uploadTask?: { abort: () => void }
) => {
  return new Promise<T>((resolve, reject) => {
    const task = uni.uploadFile({
      url: `${AppData.domain}/api${url}`,
      filePath,
      formData,
      name: "file",
      header: getRequestHeader(),
      success: resp => {
        getResponseData(
          resp,
          resp => {
            console.log(url, resp);
            resolve(resp);
          },
          reject
        );
      },
      fail: error => {
        console.error(url, error);
        reject(new Error(error.errMsg));
      },
    });
    if (uploadTask) uploadTask.abort = () => task.abort();
  });
};
